<script setup lang="ts">
import { computed, ref } from 'vue';
import { Badge, Button, Card, Empty, Modal, Space, Table, Tag } from 'ant-design-vue';
import CurveDetailView from './CurveDetailView.vue';

interface RatePoint {
  horizonDate: string;
  startDate: string | null;
  endDate: string | null;
  term: number;
  basis: number | null;
  compoundRate: number;
  discountFactor: number;
  continuesRate: number;
  sectionDiscountFactor: number;
}

interface RateCurve {
  curveName: string;
  currency: string;
  rateList: RatePoint[];
  lastRate: RatePoint;
  lastDate: string | null;
}

interface RateCurveData {
  mid: RateCurve;
  ask: RateCurve;
  bid: RateCurve;
}

interface Props {
  rateCurveMap: Record<string, RateCurveData>;
}

const props = defineProps<Props>();

// 选中的曲线和模态框状态
const selectedCurve = ref<any>(null);
const isModalVisible = ref(false);

// 计算曲线列表
const curveList = computed(() => {
  return Object.entries(props.rateCurveMap).map(([key, curve]) => ({
    key,
    name: curve.mid.curveName,
    currency: curve.mid.currency,
    data: curve
  }));
});

// 表格列定义
const overviewColumns = [
  {
    title: '曲线名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
    ellipsis: true
  },
  {
    title: '货币',
    dataIndex: 'currency',
    key: 'currency',
    width: 80,
    align: 'center' as const
  },
  {
    title: '数据点数',
    dataIndex: 'dataPoints',
    key: 'dataPoints',
    width: 100,
    align: 'center' as const
  },
  {
    title: '期限范围',
    dataIndex: 'termRange',
    key: 'termRange',
    width: 120,
    align: 'center' as const
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    align: 'center' as const
  }
];

// 获取期限范围
const getTermRange = (rateList: RatePoint[]) => {
  if (!rateList || rateList.length === 0) return '-';
  const terms = rateList.map(item => item.term).filter(term => term !== null && term !== undefined);
  if (terms.length === 0) return '-';
  const minTerm = Math.min(...terms);
  const maxTerm = Math.max(...terms);
  return minTerm === maxTerm ? `${minTerm}天` : `${minTerm}-${maxTerm}天`;
};

// 查看曲线详情
const viewCurveDetail = (curve: any) => {
  selectedCurve.value = curve;
  isModalVisible.value = true;
};

// 关闭模态框
const closeModal = () => {
  isModalVisible.value = false;
  selectedCurve.value = null;
};

// 导出曲线数据
const exportCurveData = (curve: any) => {
  const data = {
    name: curve.name,
    currency: curve.currency,
    mid: curve.data.mid.rateList,
    bid: curve.data.bid.rateList,
    ask: curve.data.ask.rateList
  };

  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `${curve.name}_curve_data.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);

  window.$message?.success('数据导出成功');
};
</script>

<template>
  <div class="rate-curve-display">
    <Card title="收益率曲线" :bordered="false">
      <div v-if="curveList.length === 0" class="empty-state">
        <Empty description="暂无收益率曲线数据" />
      </div>
      <div v-else>
        <!-- 曲线概览表格 -->
        <div class="curves-table-container">
          <div class="table-header">
            <span>共 {{ curveList.length }} 条曲线</span>
          </div>

          <!-- 曲线概览表格 -->
          <div class="overview-table">
            <Table
              :columns="overviewColumns"
              :data-source="curveList"
              :pagination="{ pageSize: 10, showSizeChanger: true, showQuickJumper: true }"
              size="small"
              :scroll="{ x: 800 }"
              row-key="key"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <Space>
                    <Button type="link" size="small" @click="viewCurveDetail(record)">查看详情</Button>
                    <Button type="link" size="small" @click="exportCurveData(record)">导出数据</Button>
                  </Space>
                </template>
                <template v-else-if="column.key === 'currency'">
                  <Tag color="blue">{{ record.currency }}</Tag>
                </template>
                <template v-else-if="column.key === 'dataPoints'">
                  <Badge :count="record.data.mid.rateList.length" color="green" />
                </template>
                <template v-else-if="column.key === 'termRange'">
                  <Tag color="orange">{{ getTermRange(record.data.mid.rateList) }}</Tag>
                </template>
              </template>
            </Table>
          </div>
        </div>

        <!-- 曲线详情模态框 -->
        <Modal
          v-model:open="isModalVisible"
          :title="`${selectedCurve?.name || ''} - 曲线详情`"
          width="80%"
          :footer="null"
          @cancel="closeModal"
        >
          <CurveDetailView v-if="selectedCurve" :curve-data="selectedCurve.data" :curve-name="selectedCurve.name" />
        </Modal>
      </div>
    </Card>
  </div>
</template>

<style scoped>
.rate-curve-display {
  .curves-table-container {
    .table-header {
      padding: 16px 0;
      border-bottom: 1px solid #f0f0f0;
      margin-bottom: 16px;

      span {
        font-weight: 500;
        color: #666;
      }
    }

    .overview-table {
      :deep(.ant-table-thead > tr > th) {
        background-color: #fafafa;
        font-weight: 600;
      }

      :deep(.ant-table-tbody > tr:hover > td) {
        background-color: #f5f5f5;
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 40px 0;
  }
}

.dark .rate-curve-display {
  .curves-table-container {
    .table-header {
      border-bottom-color: #303030;

      span {
        color: #ccc;
      }
    }
  }
}
</style>
